package com.wenx.v3auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wenx.v3auth.service.UserAuthService;
import com.wenx.v3authserverstarter.service.TokenService;
import com.wenx.v3secure.user.UserDetail;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户认证服务实现类
 * 
 * @author wenx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserAuthServiceImpl implements UserAuthService {

    private final UserDetailsService userDetailsService;
    private final PasswordEncoder passwordEncoder;
    private final TokenService tokenService;

    @Override
    public Map<String, Object> validateAndGenerateToken(String username, String password) throws Exception {
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        try {
            // 1. 加载用户详情
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            
            // 2. 验证密码
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new IllegalArgumentException("用户名或密码错误");
            }
            
            // 3. 检查账户状态
            if (!userDetails.isAccountNonExpired()) {
                throw new IllegalArgumentException("账户已过期");
            }
            if (!userDetails.isAccountNonLocked()) {
                throw new IllegalArgumentException("账户已被锁定");
            }
            if (!userDetails.isCredentialsNonExpired()) {
                throw new IllegalArgumentException("凭据已过期");
            }
            if (!userDetails.isEnabled()) {
                throw new IllegalArgumentException("账户已被禁用");
            }
            
            // 4. 创建认证对象
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
            
            // 5. 生成token响应
            Map<String, Object> tokenResponse = tokenService.generateTokenResponse(authentication);
            
            // 6. 添加成功标志
            Map<String, Object> result = new HashMap<>(tokenResponse);
            result.put("success", true);
            result.put("message", "认证成功");
            
            // 7. 添加用户基本信息
            if (userDetails instanceof UserDetail) {
                UserDetail userDetail = (UserDetail) userDetails;
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", userDetail.getId());
                userInfo.put("username", userDetail.getUsername());
                userInfo.put("email", userDetail.getEmail());
                userInfo.put("phone", userDetail.getMobile());
                userInfo.put("avatar", userDetail.getAvatar());
                userInfo.put("status", userDetail.getStatus());
                userInfo.put("permissions", userDetail.getAuthoritySet());
                result.put("user_info", userInfo);
            }
            
            log.info("用户认证成功并生成token: username={}", username);
            return result;
            
        } catch (UsernameNotFoundException e) {
            log.warn("用户不存在: username={}", username);
            throw new IllegalArgumentException("用户名或密码错误");
        } catch (Exception e) {
            log.error("用户认证失败: username={}, error={}", username, e.getMessage(), e);
            throw new Exception("认证失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getCurrentUserInfo() throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new IllegalStateException("用户未认证");
        }

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", authentication.getName());
        userInfo.put("authorities", authentication.getAuthorities().stream()
            .map(auth -> auth.getAuthority())
            .collect(Collectors.toList()));
        userInfo.put("authenticated", authentication.isAuthenticated());
        
        // 如果principal是UserDetail类型，添加更多信息
        if (authentication.getPrincipal() instanceof UserDetail) {
            UserDetail userDetail = (UserDetail) authentication.getPrincipal();
            userInfo.put("id", userDetail.getId());
            userInfo.put("email", userDetail.getEmail());
            userInfo.put("phone", userDetail.getMobile());
            userInfo.put("avatar", userDetail.getAvatar());
            userInfo.put("status", userDetail.getStatus());
        }
        
        return userInfo;
    }
}